package com.android.questions.util;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;

import java.io.File;
import java.io.OutputStream;

public class FileUtil {

    /**
     * 保存位图到相册
     *
     * @param context 上下文对象
     * @param bitmap  要保存的位图
     */
    public static void saveBitmapToAlbum(Context context, Bitmap bitmap) {
        if (bitmap == null) {
            Toast.makeText(context, "图片为空，保存失败", Toast.LENGTH_SHORT).show();
            return;
        }
        String fileName = "share-" + System.currentTimeMillis() + ".jpg";
        File file = new File(Environment.DIRECTORY_PICTURES, fileName);
        ContentValues cv = new ContentValues();
        ContentResolver resolver = context.getContentResolver();
        cv.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            cv.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
            cv.put(MediaStore.Images.Media.IS_PENDING, 0);
        } else {
            cv.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
        }
        cv.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        cv.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
        Uri insertUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv);
        if (insertUri != null) {
            OutputStream outputStream;
            try {
                outputStream = resolver.openOutputStream(insertUri);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                resolver.update(insertUri, cv, null, null);
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, insertUri);
                    context.sendBroadcast(intent);
                }
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
                Toast.makeText(context, "已保存到相册", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
